package com.huhu.levelloader;

import java.util.ArrayList;

import org.andengine.engine.Engine;
import org.andengine.engine.camera.BoundCamera;
import org.andengine.engine.camera.hud.HUD;
import org.andengine.engine.handler.timer.ITimerCallback;
import org.andengine.engine.handler.timer.TimerHandler;
import org.andengine.entity.primitive.Rectangle;
import org.andengine.entity.sprite.Sprite;
import org.andengine.entity.text.Text;
import org.andengine.extension.physics.box2d.PhysicsFactory;
import org.andengine.extension.physics.box2d.PhysicsWorld;
import org.andengine.extension.tmx.TMXObject;
import org.andengine.extension.tmx.TMXObjectGroup;
import org.andengine.extension.tmx.TMXTiledMap;
import org.andengine.input.touch.TouchEvent;
import org.andengine.opengl.vbo.VertexBufferObjectManager;

import android.util.Log;

import com.badlogic.gdx.physics.box2d.Body;
import com.badlogic.gdx.physics.box2d.BodyDef.BodyType;
import com.badlogic.gdx.physics.box2d.Contact;
import com.badlogic.gdx.physics.box2d.ContactImpulse;
import com.badlogic.gdx.physics.box2d.ContactListener;
import com.badlogic.gdx.physics.box2d.Fixture;
import com.badlogic.gdx.physics.box2d.FixtureDef;
import com.badlogic.gdx.physics.box2d.Manifold;
import com.huhu.interfaces.IPlayer;
import com.huhu.manager.ResourcesManager;
import com.huhu.manager.SceneManager;
import com.huhu.objects.AirCraft;
import com.huhu.objects.Bullet;
import com.huhu.scenes.GameScene;

public class LevelLoader1_3 extends LevelLoader{

	private HUD gameHUD;

	private final FixtureDef FIXTURE_DEF = PhysicsFactory.createFixtureDef(0,
			0.01f, 0.5f);

	private AirCraft aircraft;
	private boolean gameOverDisplayed = false;
	private boolean levelCompleteDisplayed = false;

	private Sprite clockSprite;
	
	private boolean fired = false;
	private Bullet bullets[] = new Bullet[10];
	private int count = 0;
	
	private int clockFire = 0;
	private boolean clockFired = true;
	
	private Text timeLeftText;
	private Text timeLeft;
	
	private Text killText;
	private Text enemysLeft;
	private Text enemysLeftText;
	
	private boolean clockDied = false;
	private int enemys = 25;
	private int seconds = 8;
	
	public LevelLoader1_3(Engine engine, GameScene scene, BoundCamera camera,
			PhysicsWorld physicsWorld, VertexBufferObjectManager vbom) {
		super(engine, scene, camera, physicsWorld, vbom);

		createBullets();
		engine.registerUpdateHandler(new TimerHandler(1, true, new ITimerCallback() {
			
			@Override
			public void onTimePassed(TimerHandler pTimerHandler) {
				if(seconds == 0){
					aircraft.setDie(true);
					return;
				}
				if(seconds > 0 && !clockDied){
					seconds--;
					timeLeft.setText(seconds + "");
				}
			}
		}));
	}
	
	private void createBullets(){
		for(int i = 0; i < bullets.length; i++){
			bullets[i] = new Bullet(0, 0, vbom, camera, physicsWorld);
			bullets[i].setVisible(false);
		}
	}

	protected void createHUD() {
		gameHUD = new HUD();

		final Sprite spriteMoveLeft = new Sprite(10, 520,
				resourcesManager.move_left_region, vbom) {
			@Override
			public boolean onAreaTouched(TouchEvent pSceneTouchEvent,
					float pTouchAreaLocalX, float pTouchAreaLocalY) {
				if (pSceneTouchEvent.isActionDown()) {
					aircraft.setDirection(false);
					aircraft.setRunning();
				} else {
					aircraft.setStopping();
				}
				return true;
			}
		};
		gameHUD.registerTouchArea(spriteMoveLeft);
		gameHUD.attachChild(spriteMoveLeft);

		final Sprite spriteMoveRight = new Sprite(135, 520,
				resourcesManager.move_right_region, vbom) {
			@Override
			public boolean onAreaTouched(TouchEvent pSceneTouchEvent,
					float pTouchAreaLocalX, float pTouchAreaLocalY) {
				if (pSceneTouchEvent.isActionDown()) {
					aircraft.setDirection(true);
					aircraft.setRunning();
				} else {
					aircraft.setStopping();
				}
				return true;
			}
		};
		gameHUD.registerTouchArea(spriteMoveRight);
		gameHUD.attachChild(spriteMoveRight);
		
		final Sprite spriteFire = new Sprite(876, 520,
				resourcesManager.fire_region, vbom) {
			@Override
			public boolean onAreaTouched(TouchEvent pSceneTouchEvent,
					float pTouchAreaLocalX, float pTouchAreaLocalY) {
				if (pSceneTouchEvent.isActionDown() && !fired && !aircraft.isDie()) {
					fired = true;
					bullets[count] = new Bullet(aircraft.getCenterX(), aircraft.getY(), vbom,
							camera, physicsWorld);
					scene.attachChild(bullets[count]);
					bullets[count].fire();
					count ++;
					if(count >= 10){
						count = 0;
					}
					engine.registerUpdateHandler(new TimerHandler(0.25f, new ITimerCallback() {
						
						@Override
						public void onTimePassed(TimerHandler pTimerHandler) {
							engine.unregisterUpdateHandler(pTimerHandler);
							fired = false;
						}
					}));
				}
				return true;
			}
		};
		gameHUD.registerTouchArea(spriteFire);
		gameHUD.attachChild(spriteFire);

		final Sprite spriteBack = new Sprite(10, 10,
				resourcesManager.back_region, vbom) {
			@Override
			public boolean onAreaTouched(TouchEvent pSceneTouchEvent,
					float pTouchAreaLocalX, float pTouchAreaLocalY) {
				SceneManager.getInstance().getCurrentScene().onBackKeyPressed();
				return true;
			}
		};
		gameHUD.registerTouchArea(spriteBack);
		gameHUD.attachChild(spriteBack);

		camera.setHUD(gameHUD);
	}
	
//	private void cre

	public IPlayer createPlatform(TMXTiledMap mTMXTiledMap) {
		final ArrayList<TMXObjectGroup> mTMXObjectGroups = mTMXTiledMap
				.getTMXObjectGroups();
		for (TMXObjectGroup mTMXObjectGroup : mTMXObjectGroups) {
			if (mTMXObjectGroup.getTMXObjectGroupProperties()
					.containsTMXProperty("platformobject", "true")) {
				for (TMXObject mTMXObject : mTMXObjectGroup.getTMXObjects()) {
					Rectangle rectangle = new Rectangle(mTMXObject.getX(),
							mTMXObject.getY(), mTMXObject.getWidth(),
							mTMXObject.getHeight(), vbom);
					Body bodyPlatform = PhysicsFactory.createBoxBody(
							physicsWorld, rectangle, BodyType.StaticBody,
							FIXTURE_DEF);
					bodyPlatform.setUserData("body_platform_data");
					rectangle.setVisible(false);
					scene.attachChild(rectangle);
				}
			} else if (mTMXObjectGroup.getTMXObjectGroupProperties()
					.containsTMXProperty("object", "true")) {
				for (TMXObject mTMXObject : mTMXObjectGroup.getTMXObjects()) {
					float x = mTMXObject.getX();
					float y = mTMXObject.getY();
					if (mTMXObject.getName().equals("girl")) {
						final Sprite girlSprite = new Sprite(mTMXObject.getX(),
								mTMXObject.getY(),
								resourcesManager.girl_region, vbom);
						scene.attachChild(girlSprite);
					}
					if (mTMXObject.getName().equals("clock")) {
						resourcesManager.loadClockGraphics();
						clockSprite = new Sprite(mTMXObject.getX(),
								mTMXObject.getY(),
								resourcesManager.clock_region, vbom){
							@Override
							protected void onManagedUpdate(
									float pSecondsElapsed) {
								// TODO Auto-generated method stub
								super.onManagedUpdate(pSecondsElapsed);
								
								for(int i = 0; i < bullets.length; i++){
									if(collidesWith(bullets[i])){
										
										bullets[i].setVisible(false);
										bullets[i].setY(0);
										clockFire ++;
										Log.d("Collides", clockFire + "");
										if(clockFire == 4){
											resourcesManager.replaceClockCry();
										}
										if(clockFire == 8){
											clockDied = true;
											resourcesManager.replaceClockDead();
										}
									}
								}
							}
						};
						scene.attachChild(clockSprite);
					}
					if(mTMXObject.getName().equals("killtext")){
						killText = new Text(x-40, y, resourcesManager.gameFont, "Kill them all\nin 8 seconds", vbom);
						killText.setScale(0.8f);
						scene.attachChild(killText);
					}
					if(mTMXObject.getName().equals("enemysleft")){
						enemysLeft = new Text(x + 32, y, resourcesManager.gameFont, enemys+"", vbom);
						enemysLeft.setScale(3);
						scene.attachChild(enemysLeft);
					}
					if(mTMXObject.getName().equals("enemyslefttext")){
						enemysLeftText = new Text(x - 16, y, resourcesManager.gameFont, "Enemy Left", vbom);
						scene.attachChild(enemysLeftText);
					}
					if(mTMXObject.getName().equals("timeleft")){
						timeLeft = new Text(x + 32, y, resourcesManager.gameFont, seconds+"", vbom);
						timeLeft.setScale(5);
						scene.attachChild(timeLeft);
					}
					if(mTMXObject.getName().equals("timelefttext")){
						timeLeftText = new Text(x, y, resourcesManager.gameFont, "Time Left", vbom);
						scene.attachChild(timeLeftText);
					}
					
					if (mTMXObject.getName().equals("player")) {
						resourcesManager.loadAircraftGraphics();
						if (!SceneManager.saveActivte) {
							SceneManager.savePositionX = mTMXObject.getX();
							SceneManager.savePositionY = mTMXObject.getY();
						}
						aircraft = new AirCraft(SceneManager.savePositionX,
								SceneManager.savePositionY, vbom, camera,
								physicsWorld) {

							@Override
							public void onDie() {
								if (!gameOverDisplayed) {
									gameOverDisplayed = true;
									if (!ResourcesManager.getInstance().die_sound
											.isPlaying()) {
										ResourcesManager.getInstance().die_sound
												.play();
									}
									scene.displayGamOver();
								}

							}
						};

						scene.attachChild(aircraft);
					}
				}

			} else if (mTMXObjectGroup.getTMXObjectGroupProperties()
					.containsTMXProperty("enemysobject", "true")) {
				for (TMXObject mTMXObject : mTMXObjectGroup.getTMXObjects()) {
					final Sprite enemySprite = new Sprite(mTMXObject.getX(),
							mTMXObject.getY(), resourcesManager.slime1_region,
							vbom) {
						@Override
						protected void onManagedUpdate(float pSecondsElapsed) {
							// TODO Auto-generated method stub
							super.onManagedUpdate(pSecondsElapsed);
							for(int i = 0; i < bullets.length; i++){
								if (collidesWith(bullets[i])) {
									Log.d("Collides", i + "");
									bullets[i].setStopped(true);
									setVisible(false);
									enemys --;
									enemysLeft.setText(enemys + "");
									bullets[i].setVisible(false);
									setIgnoreUpdate(true);
									if(enemys == 0){
										scene.displayLevelComplete(SceneManager.currentLevel);
									}
								}
							}
						}
					};
					scene.attachChild(enemySprite);
				}
			}
		}
		return aircraft;
	}

	protected ContactListener contactListener() {
		ContactListener contactListner = new ContactListener() {

			@Override
			public void preSolve(Contact contact, Manifold oldManifold) {
				// TODO Auto-generated method stub

			}

			@Override
			public void postSolve(Contact contact, ContactImpulse impulse) {
				// TODO Auto-generated method stub

			}

			@Override
			public void endContact(Contact contact) {
				final Fixture x1 = contact.getFixtureA();
				final Fixture x2 = contact.getFixtureB();
				if (x1.getBody().getUserData() != null
						&& x2.getBody().getUserData() != null) {
					Object x1_bodyData = x1.getBody().getUserData();
					Object x2_bodyData = x2.getBody().getUserData();
					if (x1_bodyData.equals("player")
							|| x2_bodyData.equals("player")) {
						aircraft.decreaseFootContacts();
					}
				}

			}

			@Override
			public void beginContact(Contact contact) {
				final Fixture x1 = contact.getFixtureA();
				final Fixture x2 = contact.getFixtureB();
				if (x1.getBody().getUserData() != null
						&& x2.getBody().getUserData() != null) {
					Object x1_bodyData = x1.getBody().getUserData();
					Object x2_bodyData = x2.getBody().getUserData();
					Log.d("Contact", x1_bodyData + " " + x2_bodyData);
					if (x1_bodyData.equals("player")
							|| x2_bodyData.equals("player")) {
						aircraft.increaseFootContacts();
					}
				}
			}
		};
		return contactListner;
	}
}
